<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use Exception;
use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\Ads as ModelAds;
use Hangpu888\Hpadmin\model\AdsCate;
use Hangpu888\Hpadmin\utils\builder\FormBuilder;
use Hangpu888\Hpadmin\utils\builder\ListBuilder;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\utils\manager\UploadsManager;
use Hangpu888\Hpadmin\validate\Ads as ValidateAds;
use Shopwwi\WebmanFilesystem\Facade\Storage;

class Ads extends Controller
{
    /**
     * 显示列表
     *
     * @return void
     */
    public function index()
    {
        $list = ModelAds::with(['category'])
        ->order('id desc')
        ->paginate()
        ->each(function($item){
            $item->imgurl = Storage::url($item->imgurl);
            $item->cate_title = $item->category ? $item->category->title : '--';
            $item->ad_size = $item->category ? "高：{$item->category->height} - 宽：{$item->category->width}" : '--';
            return $item;
        })
        ->toArray();
        $builder = new ListBuilder;
        $data = $builder
            ->addColumn('rightButtonList', '操作', [
                'type'              => 'template',
                'template'          => 'rightButtonList',
                'width'             => '180'
            ])
            ->addTopButton('add', '添加', [
                'title'             => '添加数据',
                'api'               => '/hpadmin/Ads/add',
            ])
            ->addRightButton('edit', '修改', [
                'api'               => '/hpadmin/Ads/edit',
                'title'             => '修改',
            ], [
                'type'              => 'text'
            ])
            ->addRightButton('delete', '删除', [
                'api'               => '/hpadmin/Ads/del',
                'method'            => 'delete',
                'title'             => '温馨提示',
                'content'           => '是否确认删除该数据？',
                'type'              => 'confirm',
            ], [
                'type'              => 'text'
            ])
            ->addColumn('id', '序号', [
                'width'             => '80',
            ])
            ->addColumn('ctime', '添加时间', [
                'width'             => '180',
            ])
            ->addColumn('utime', '更新时间', [
                'width'             => '180',
            ])
            ->addColumn('cate_title', '所属分类')
            ->addColumn('title', '广告标题')
            ->addColumn('imgurl', '图片广告',[
                'type'              => 'image',
            ])
            ->addColumn('url', '跳转地址')
            ->addColumn('ad_size', '广告尺寸')
            ->addColumn('sort', '广告排序')
            ->setData($list['data'])
            ->setDataPage($list['total'], $list['per_page'], $list['current_page'])
            ->create();
        return Json::successRes($data);
    }

    /**
     * 显示添加表单
     *
     * @return void
     */
    public function add()
    {
        try {
            if (request()->method() == 'POST') {
                // 获取数据
                $post = request()->post();
    
                // 数据验证
                hpValidate(new ValidateAds,$post);
                
                // 重组数据
                $uploadManager = new UploadsManager;
                $post['imgurl'] = $uploadManager->strReplaceUrl($post['imgurl']);
                
                // 数据操作
                $model = new ModelAds;
                foreach ($post as $field => $value) {
                    $model->$field = $value;
                }
                if ($model->save()) {
                    return Json::success('添加成功');
                } else {
                    return Json::fail('添加失败');
                }
            } else {
                $category = AdsCate::order('id desc')
                ->field('tag as value,title as label')
                ->select()
                ->toArray();
                $open_type = [
                    [
                        'label'     => '保留当前页面跳转',
                        'value'     => 'navigateTo',
                    ],
                    [
                        'label'     => '关闭当前页面跳转',
                        'value'     => 'redirectTo',
                    ],
                    [
                        'label'     => '关闭所有页面跳转',
                        'value'     => 'reLaunch',
                    ],
                    [
                        'label'     => '跳转至四主页',
                        'value'     => 'switchTab',
                    ],
                    [
                        'label'     => '内置浏览器打开',
                        'value'     => 'webView',
                    ],
                ];
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('post')
                    ->addRow('tag', 'select', '所属分类', '', [
                        'options'           => $category,
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('sort', 'input', '广告排序', '100', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('url', 'input', '跳转地址', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('open_type', 'select', '跳转方式', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                        'options'           => $open_type
                    ])
                    ->addRow('title', 'input', '广告标题')
                    ->addRow('imgurl', 'custom', '广告图片', '', [
                        'type'              => 'uploadify',
                        'extra'             => [
                            'props'         => [
                                'format'    => 'image',
                                'btn_text'  => '选择图片',
                                'ext'       => 'jpg,png,gif',
                                'width'     => 0,
                                'height'    => 0,
                            ],
                            'col'               => [
                                'span'          => 12
                            ],
                        ],
                    ])
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 显示编辑表单
     *
     * @return void
     */
    public function edit()
    {
        try {
            $id = request()->get('id');
            $model = ModelAds::where(['id'=> $id])->find();
            if (!$model) {
                throw new Exception('该数据错误');
            }
            if (request()->method() == 'PUT') {
                // 获取数据
                $post = request()->post();
    
                // 数据验证
                hpValidate(new ValidateAds,$post);

                // 重组数据
                $uploadManager = new UploadsManager;
                $post['imgurl'] = $uploadManager->strReplaceUrl($post['imgurl']);
                
                // 数据操作
                foreach ($post as $field => $value) {
                    $model->$field = $value;
                }
                if ($model->save()) {
                    return Json::success('修改成功');
                } else {
                    return Json::fail('修改失败');
                }
            } else {
                if (!$model) {
                    return Json::fail('找不到该数据');
                }
                $info = $model->toArray();
                $info['imgurl'] = Storage::url($info['imgurl']);
                $category = AdsCate::order('id desc')
                ->field('tag as value,title as label')
                ->select()
                ->toArray();
                $open_type = [
                    [
                        'label'     => '保留当前页面跳转',
                        'value'     => 'navigateTo',
                    ],
                    [
                        'label'     => '关闭当前页面跳转',
                        'value'     => 'redirectTo',
                    ],
                    [
                        'label'     => '关闭所有页面跳转',
                        'value'     => 'reLaunch',
                    ],
                    [
                        'label'     => '跳转至四主页',
                        'value'     => 'switchTab',
                    ],
                    [
                        'label'     => '内置浏览器打开',
                        'value'     => 'webView',
                    ],
                ];
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('put')
                    ->addRow('tag', 'select', '所属分类', '', [
                        'options'           => $category,
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('sort', 'input', '广告排序', '100', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('url', 'input', '跳转地址', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                    ])
                    ->addRow('open_type', 'select', '跳转方式', '', [
                        'col'               => [
                            'span'          => 12
                        ],
                        'options'           => $open_type
                    ])
                    ->addRow('title', 'input', '广告标题')
                    ->addRow('imgurl', 'custom', '广告图片', '', [
                        'type'              => 'uploadify',
                        'extra'             => [
                            'props'         => [
                                'format'    => 'images',
                                'btn_text'  => '选择图片',
                                'limit'     => 3,
                                'ext'       => 'jpg,png,gif',
                                'width'     => 0,
                                'height'    => 0,
                            ],
                            'col'               => [
                                'span'          => 12
                            ],
                        ],
                    ])
                    ->setFormData($info)
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 删除数据
     *
     * @return void
     */
    public function del()
    {
        $id = request()->get('id');
        $model = ModelAds::where(['id' => $id])->find();
        if (!$model) {
            return Json::fail('该数据不存在');
        }
        if ($model->delete()) {
            return Json::success('删除成功');
        } else {
            return Json::fail('删除失败');
        }
    }
}
